<template>
  <div id="staModuleSeDiv">
    <Breadcrumb content="仪器注册" />
    <div class="bodyContent">

          <Splitpanes horizontal>
            <Pane size="80">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-upload" content="上传注册码" @click="upload"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="手动新增注册码" @click="addStaModelDialog"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="modulTable">
                <vxe-table ref="staModuleTableRef" class="mytable-scrollbar staModuleTableClazz" border="inner" align="center" height="auto" :data="staModuleList" :loading="tloading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column field="staInstrCode" title="标准编号"> </vxe-column>
                  <vxe-column field="instrCode" title="仪器代号"> </vxe-column>
                  <vxe-column field="instrName" title="仪器名称"> </vxe-column>
                  <vxe-column field="instrCalled" title="仪器简介"> </vxe-column>
                  <vxe-column field="instrMark" title="仪器型号"> </vxe-column>
                  <vxe-column field="instrClass" title="仪器类别">
                    <template #default="{ row }">
                      <span>{{ formatCommon(instrClassDict, row.instrClass) }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="isQc" title="是否质控" width="80">
                    <template #default="{ row }">
                      <vxe-checkbox v-model="row.isQc"></vxe-checkbox>
                    </template>
                  </vxe-column>
                  <vxe-column field="createTime" :formatter="formatOperateTime" title="操作时间"></vxe-column>
                  <vxe-column field="instrRegister" title="注册码"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="20">
              <div class="modulTable1">
                <vxe-table ref="failModuleTableRef" class="mytable-scrollbar staModuleTableClazz" border="inner" align="center" height="auto" :data="failStaModuleList" :loading="tloading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>

                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span >注册失败</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="staModCode" title="标准编号"></vxe-column>
                  <vxe-column field="instrRegister" title="注册码"></vxe-column>
                  <vxe-column field="createTime" :formatter="formatOperateTime" title="操作时间"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>


      <vxe-modal v-model="isModelVisiable" width="25vw" height="35vh" show-footer :mask="false" @close="cancelModelEvent">
        <template #title>
          <span>上传注册码</span>
        </template>
        <template #default>
          <div class="form-panel">
            <vxe-form :data="staModelForm" title-width="80">
              <vxe-form-item title="模块密文" span="24" field="modelCode">
                <template #default="{ data }">
                  <vxe-textarea type="textarea" v-model="data.cipherText" placeholder="模块密文" :autosize="{ minRows: 7 }"></vxe-textarea>
                </template>
              </vxe-form-item>
            </vxe-form>
          </div>
        </template>
        <template #footer>
          <vxe-button type="text" class="button-white" @click="cancelModelEvent">取消</vxe-button>
          <vxe-button type="text" class="button-blue" @click="confirmModelEvent">确定</vxe-button>
        </template>
      </vxe-modal>

    </div>

  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import SelectIcon from '@/components/SelectIcon.vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import {formatDateTime, IsEmpty} from "@/utils/common";
import {GetPatTypeList} from "@/utils/BasicDictsHelper";
import {isEmpty} from "lodash";
import {VxeMessage, VxeNotifyType} from "@/utils/CommonMessage"; //面包屑
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let qloading = ref(false); //右侧质控表格加载+刷新
let isModelVisiable = ref(false);
let activeName = ref('first');
let refselectIcon = ref(null);
let staModuleList: any = reactive([]);
let failStaModuleList: any = reactive([]);
let instrClassDict = reactive([]); //仪器大类字典
let workGroupList = reactive([]); //仪器大类字典
let staModelForm = reactive({
  cipherText: ''

});
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 初始化数据
onMounted(() => {
  getDataList();
  getDictItemsList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['YQDL', 'JYGZZ'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...maintainTypes.detailDataList);
  const maintainStatues = dictTreeTypeItems.data.find((item) => item.code === 'JYGZZ');
  workGroupList.push(...maintainStatues.detailDataList);
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
function getDataList() {
  staModuleList.length=0;
  failStaModuleList.length=0;
  tloading.value = true;
  let url = '/lis/instrSetup/findStaInsterLogList';
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res.status.code == 1){
          if (res.data.length>0){
            res.data.forEach((item:any) => {
              if (item.state == '0'){
                failStaModuleList.push(item);
              }else {
                staModuleList.push(item);
              }
            });
          }
          tloading.value = false;
        }
      })
      .catch((err) => {
        (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
      });
}


function upload() {
  const $grid = proxy.$refs.staModuleTableRef as any;
  // 读取附件
  $grid
      .readFile({
        multiple: true,
        types: ['txt']
      })
      .then((params) => {
        const { files } = params;
        // 解析数据并显示
        Array.from(files).forEach((file: any) => {
          uploadByUrl(file);
        });
      });
}

function addStaModelDialog() {
  isModelVisiable.value = true;
}
function cancelModelEvent() {
  staModelForm.cipherText="";
  isModelVisiable.value = false;
}

function uploadByUrl(file) {
  tloading.value = true;
  staModuleList.length=0;
  failStaModuleList.length=0;
  let url = '/lis/instrSetup/uploadRegisterFile';
  const fd = new FormData();
  fd.append('file', file);

  proxy.$http
      .post(url, fd)
      .then((res: any) => {
        if (res.status.code == 1){
          getDataList();
        }else {
          getDataList();
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        tloading.value = false;
      })
      .catch((err) => {
        (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
      });
}
function confirmModelEvent() {
  if (IsEmpty(staModelForm.cipherText)){
    VxeMessage('请输入模块密文', VxeNotifyType.error);
    return;
  }
  tloading.value = true;
  staModuleList.length=0;
  failStaModuleList.length=0;
  let url = '/lis/instrSetup/uploadRegisterCipherText';
  const postData = {
    cipherText: staModelForm.cipherText
  };
  proxy.$http
      .post(url,postData)
      .then((res: any) => {
        if (res.status.code == 1){
          getDataList();
        }else {
          getDataList();
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        isModelVisiable.value = false;
        tloading.value = false;
      })
      .catch((err) => {
        (this as any).$XModal.message({ content: err.data.error.message, status: 'warning' });
      });
}
// 格式化日期时间
function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}

</script>

<style lang="scss" scoped>
#staModuleSeDiv {
  height: 100%;
  width: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 5px 5px 0;
    }
    //右侧质控项目表格
    .tableBox {
      height: calc(100%);
      background-color: $base-white;
    }
  }
  //右侧质控项目表格
  .modulTable {
    height: calc(100% - 70px);
    background-color: $base-white;
  }
  .modulTable1 {
    height: calc(100%);
    background-color: $base-white;
  }
}
</style>